/**
 * 
 */
package com.hexacta.hrs.web.util;

import javax.servlet.http.HttpServletRequestWrapper;

import org.vectrics.common.util.StringUtils;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.user.Person;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

/**
 * @author mfunes
 * 
 */
public class ContextAvailableInterceptor extends AbstractInterceptor {

    private static final long serialVersionUID = -6791033336719074273L;

    /** {@inheritDoc} */
    @Override
    public String intercept(final ActionInvocation invocation) throws Exception {
        try {
            Person authPerson = CoreServiceLocator.getUserAuthService().getAuthorizedPerson(
                    invocation.getInvocationContext().getSession());
            if (authPerson != null) {
                HttpServletRequestWrapper httpServletRequestWrapper = (HttpServletRequestWrapper) invocation
                        .getInvocationContext().get("com.opensymphony.xwork2.dispatcher.HttpServletRequest");
                // boolean per = CoreServiceLocator.getUserAuthService().
                // doesUserHavePagePrivilege(request, person, domain)
                String uri = StringUtils.clearURL(httpServletRequestWrapper.getRequestURI());

                if (CoreServiceLocator.getUserAuthService().doesUserHavePagePrivilege(uri, authPerson)) {
                    if (ThreadProperties.getPerson() == null
                            || ThreadProperties.getPerson().getId() != authPerson.getId()) {
                        ThreadProperties.setPerson(authPerson);
                    }
                    return invocation.invoke();
                }
            }
        } catch (org.vectrics.SystemException ex) {
        }
        return "contextUnAvailable";
    }
}
